// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"server/components/models/ent/forecast"
	"server/components/models/ent/predicate"
	"server/components/models/ent/region"
	"server/components/models/ent/weather"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// WeatherQuery is the builder for querying Weather entities.
type WeatherQuery struct {
	config
	ctx          *QueryContext
	order        []weather.OrderOption
	inters       []Interceptor
	predicates   []predicate.Weather
	withRegion   *RegionQuery
	withForecast *ForecastQuery
	withFKs      bool
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the WeatherQuery builder.
func (wq *WeatherQuery) Where(ps ...predicate.Weather) *WeatherQuery {
	wq.predicates = append(wq.predicates, ps...)
	return wq
}

// Limit the number of records to be returned by this query.
func (wq *WeatherQuery) Limit(limit int) *WeatherQuery {
	wq.ctx.Limit = &limit
	return wq
}

// Offset to start from.
func (wq *WeatherQuery) Offset(offset int) *WeatherQuery {
	wq.ctx.Offset = &offset
	return wq
}

// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (wq *WeatherQuery) Unique(unique bool) *WeatherQuery {
	wq.ctx.Unique = &unique
	return wq
}

// Order specifies how the records should be ordered.
func (wq *WeatherQuery) Order(o ...weather.OrderOption) *WeatherQuery {
	wq.order = append(wq.order, o...)
	return wq
}

// QueryRegion chains the current query on the "region" edge.
func (wq *WeatherQuery) QueryRegion() *RegionQuery {
	query := (&RegionClient{config: wq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := wq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := wq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(weather.Table, weather.FieldID, selector),
			sqlgraph.To(region.Table, region.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, weather.RegionTable, weather.RegionColumn),
		)
		fromU = sqlgraph.SetNeighbors(wq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryForecast chains the current query on the "forecast" edge.
func (wq *WeatherQuery) QueryForecast() *ForecastQuery {
	query := (&ForecastClient{config: wq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := wq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := wq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(weather.Table, weather.FieldID, selector),
			sqlgraph.To(forecast.Table, forecast.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, weather.ForecastTable, weather.ForecastColumn),
		)
		fromU = sqlgraph.SetNeighbors(wq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// First returns the first Weather entity from the query.
// Returns a *NotFoundError when no Weather was found.
func (wq *WeatherQuery) First(ctx context.Context) (*Weather, error) {
	nodes, err := wq.Limit(1).All(setContextOp(ctx, wq.ctx, "First"))
	if err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nil, &NotFoundError{weather.Label}
	}
	return nodes[0], nil
}

// FirstX is like First, but panics if an error occurs.
func (wq *WeatherQuery) FirstX(ctx context.Context) *Weather {
	node, err := wq.First(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return node
}

// FirstID returns the first Weather ID from the query.
// Returns a *NotFoundError when no Weather ID was found.
func (wq *WeatherQuery) FirstID(ctx context.Context) (id int64, err error) {
	var ids []int64
	if ids, err = wq.Limit(1).IDs(setContextOp(ctx, wq.ctx, "FirstID")); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{weather.Label}
		return
	}
	return ids[0], nil
}

// FirstIDX is like FirstID, but panics if an error occurs.
func (wq *WeatherQuery) FirstIDX(ctx context.Context) int64 {
	id, err := wq.FirstID(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return id
}

// Only returns a single Weather entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Weather entity is found.
// Returns a *NotFoundError when no Weather entities are found.
func (wq *WeatherQuery) Only(ctx context.Context) (*Weather, error) {
	nodes, err := wq.Limit(2).All(setContextOp(ctx, wq.ctx, "Only"))
	if err != nil {
		return nil, err
	}
	switch len(nodes) {
	case 1:
		return nodes[0], nil
	case 0:
		return nil, &NotFoundError{weather.Label}
	default:
		return nil, &NotSingularError{weather.Label}
	}
}

// OnlyX is like Only, but panics if an error occurs.
func (wq *WeatherQuery) OnlyX(ctx context.Context) *Weather {
	node, err := wq.Only(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// OnlyID is like Only, but returns the only Weather ID in the query.
// Returns a *NotSingularError when more than one Weather ID is found.
// Returns a *NotFoundError when no entities are found.
func (wq *WeatherQuery) OnlyID(ctx context.Context) (id int64, err error) {
	var ids []int64
	if ids, err = wq.Limit(2).IDs(setContextOp(ctx, wq.ctx, "OnlyID")); err != nil {
		return
	}
	switch len(ids) {
	case 1:
		id = ids[0]
	case 0:
		err = &NotFoundError{weather.Label}
	default:
		err = &NotSingularError{weather.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (wq *WeatherQuery) OnlyIDX(ctx context.Context) int64 {
	id, err := wq.OnlyID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// All executes the query and returns a list of Weathers.
func (wq *WeatherQuery) All(ctx context.Context) ([]*Weather, error) {
	ctx = setContextOp(ctx, wq.ctx, "All")
	if err := wq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*Weather, *WeatherQuery]()
	return withInterceptors[[]*Weather](ctx, wq, qr, wq.inters)
}

// AllX is like All, but panics if an error occurs.
func (wq *WeatherQuery) AllX(ctx context.Context) []*Weather {
	nodes, err := wq.All(ctx)
	if err != nil {
		panic(err)
	}
	return nodes
}

// IDs executes the query and returns a list of Weather IDs.
func (wq *WeatherQuery) IDs(ctx context.Context) (ids []int64, err error) {
	if wq.ctx.Unique == nil && wq.path != nil {
		wq.Unique(true)
	}
	ctx = setContextOp(ctx, wq.ctx, "IDs")
	if err = wq.Select(weather.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (wq *WeatherQuery) IDsX(ctx context.Context) []int64 {
	ids, err := wq.IDs(ctx)
	if err != nil {
		panic(err)
	}
	return ids
}

// Count returns the count of the given query.
func (wq *WeatherQuery) Count(ctx context.Context) (int, error) {
	ctx = setContextOp(ctx, wq.ctx, "Count")
	if err := wq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return withInterceptors[int](ctx, wq, querierCount[*WeatherQuery](), wq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (wq *WeatherQuery) CountX(ctx context.Context) int {
	count, err := wq.Count(ctx)
	if err != nil {
		panic(err)
	}
	return count
}

// Exist returns true if the query has elements in the graph.
func (wq *WeatherQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, wq.ctx, "Exist")
	switch _, err := wq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("ent: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (wq *WeatherQuery) ExistX(ctx context.Context) bool {
	exist, err := wq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the WeatherQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (wq *WeatherQuery) Clone() *WeatherQuery {
	if wq == nil {
		return nil
	}
	return &WeatherQuery{
		config:       wq.config,
		ctx:          wq.ctx.Clone(),
		order:        append([]weather.OrderOption{}, wq.order...),
		inters:       append([]Interceptor{}, wq.inters...),
		predicates:   append([]predicate.Weather{}, wq.predicates...),
		withRegion:   wq.withRegion.Clone(),
		withForecast: wq.withForecast.Clone(),
		// clone intermediate query.
		sql:  wq.sql.Clone(),
		path: wq.path,
	}
}

// WithRegion tells the query-builder to eager-load the nodes that are connected to
// the "region" edge. The optional arguments are used to configure the query builder of the edge.
func (wq *WeatherQuery) WithRegion(opts ...func(*RegionQuery)) *WeatherQuery {
	query := (&RegionClient{config: wq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	wq.withRegion = query
	return wq
}

// WithForecast tells the query-builder to eager-load the nodes that are connected to
// the "forecast" edge. The optional arguments are used to configure the query builder of the edge.
func (wq *WeatherQuery) WithForecast(opts ...func(*ForecastQuery)) *WeatherQuery {
	query := (&ForecastClient{config: wq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	wq.withForecast = query
	return wq
}

// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
//	var v []struct {
//		Temperature float64 `json:"temperature,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.Weather.Query().
//		GroupBy(weather.FieldTemperature).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (wq *WeatherQuery) GroupBy(field string, fields ...string) *WeatherGroupBy {
	wq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WeatherGroupBy{build: wq}
	grbuild.flds = &wq.ctx.Fields
	grbuild.label = weather.Label
	grbuild.scan = grbuild.Scan
	return grbuild
}

// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
//	var v []struct {
//		Temperature float64 `json:"temperature,omitempty"`
//	}
//
//	client.Weather.Query().
//		Select(weather.FieldTemperature).
//		Scan(ctx, &v)
func (wq *WeatherQuery) Select(fields ...string) *WeatherSelect {
	wq.ctx.Fields = append(wq.ctx.Fields, fields...)
	sbuild := &WeatherSelect{WeatherQuery: wq}
	sbuild.label = weather.Label
	sbuild.flds, sbuild.scan = &wq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WeatherSelect configured with the given aggregations.
func (wq *WeatherQuery) Aggregate(fns ...AggregateFunc) *WeatherSelect {
	return wq.Select().Aggregate(fns...)
}

func (wq *WeatherQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range wq.inters {
		if inter == nil {
			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, wq); err != nil {
				return err
			}
		}
	}
	for _, f := range wq.ctx.Fields {
		if !weather.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if wq.path != nil {
		prev, err := wq.path(ctx)
		if err != nil {
			return err
		}
		wq.sql = prev
	}
	return nil
}

func (wq *WeatherQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Weather, error) {
	var (
		nodes       = []*Weather{}
		withFKs     = wq.withFKs
		_spec       = wq.querySpec()
		loadedTypes = [2]bool{
			wq.withRegion != nil,
			wq.withForecast != nil,
		}
	)
	if wq.withRegion != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, weather.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*Weather).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &Weather{config: wq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, wq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := wq.withRegion; query != nil {
		if err := wq.loadRegion(ctx, query, nodes, nil,
			func(n *Weather, e *Region) { n.Edges.Region = e }); err != nil {
			return nil, err
		}
	}
	if query := wq.withForecast; query != nil {
		if err := wq.loadForecast(ctx, query, nodes,
			func(n *Weather) { n.Edges.Forecast = []*Forecast{} },
			func(n *Weather, e *Forecast) { n.Edges.Forecast = append(n.Edges.Forecast, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (wq *WeatherQuery) loadRegion(ctx context.Context, query *RegionQuery, nodes []*Weather, init func(*Weather), assign func(*Weather, *Region)) error {
	ids := make([]int64, 0, len(nodes))
	nodeids := make(map[int64][]*Weather)
	for i := range nodes {
		if nodes[i].weather_region == nil {
			continue
		}
		fk := *nodes[i].weather_region
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(region.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "weather_region" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (wq *WeatherQuery) loadForecast(ctx context.Context, query *ForecastQuery, nodes []*Weather, init func(*Weather), assign func(*Weather, *Forecast)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int64]*Weather)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	query.withFKs = true
	query.Where(predicate.Forecast(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(weather.ForecastColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.weather_forecast
		if fk == nil {
			return fmt.Errorf(`foreign-key "weather_forecast" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "weather_forecast" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

func (wq *WeatherQuery) sqlCount(ctx context.Context) (int, error) {
	_spec := wq.querySpec()
	_spec.Node.Columns = wq.ctx.Fields
	if len(wq.ctx.Fields) > 0 {
		_spec.Unique = wq.ctx.Unique != nil && *wq.ctx.Unique
	}
	return sqlgraph.CountNodes(ctx, wq.driver, _spec)
}

func (wq *WeatherQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := sqlgraph.NewQuerySpec(weather.Table, weather.Columns, sqlgraph.NewFieldSpec(weather.FieldID, field.TypeInt64))
	_spec.From = wq.sql
	if unique := wq.ctx.Unique; unique != nil {
		_spec.Unique = *unique
	} else if wq.path != nil {
		_spec.Unique = true
	}
	if fields := wq.ctx.Fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, weather.FieldID)
		for i := range fields {
			if fields[i] != weather.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
			}
		}
	}
	if ps := wq.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if limit := wq.ctx.Limit; limit != nil {
		_spec.Limit = *limit
	}
	if offset := wq.ctx.Offset; offset != nil {
		_spec.Offset = *offset
	}
	if ps := wq.order; len(ps) > 0 {
		_spec.Order = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	return _spec
}

func (wq *WeatherQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(wq.driver.Dialect())
	t1 := builder.Table(weather.Table)
	columns := wq.ctx.Fields
	if len(columns) == 0 {
		columns = weather.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if wq.sql != nil {
		selector = wq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if wq.ctx.Unique != nil && *wq.ctx.Unique {
		selector.Distinct()
	}
	for _, p := range wq.predicates {
		p(selector)
	}
	for _, p := range wq.order {
		p(selector)
	}
	if offset := wq.ctx.Offset; offset != nil {
		// limit is mandatory for offset clause. We start
		// with default value, and override it below if needed.
		selector.Offset(*offset).Limit(math.MaxInt32)
	}
	if limit := wq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// WeatherGroupBy is the group-by builder for Weather entities.
type WeatherGroupBy struct {
	selector
	build *WeatherQuery
}

// Aggregate adds the given aggregation functions to the group-by query.
func (wgb *WeatherGroupBy) Aggregate(fns ...AggregateFunc) *WeatherGroupBy {
	wgb.fns = append(wgb.fns, fns...)
	return wgb
}

// Scan applies the selector query and scans the result into the given value.
func (wgb *WeatherGroupBy) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, wgb.build.ctx, "GroupBy")
	if err := wgb.build.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*WeatherQuery, *WeatherGroupBy](ctx, wgb.build, wgb, wgb.build.inters, v)
}

func (wgb *WeatherGroupBy) sqlScan(ctx context.Context, root *WeatherQuery, v any) error {
	selector := root.sqlQuery(ctx).Select()
	aggregation := make([]string, 0, len(wgb.fns))
	for _, fn := range wgb.fns {
		aggregation = append(aggregation, fn(selector))
	}
	if len(selector.SelectedColumns()) == 0 {
		columns := make([]string, 0, len(*wgb.flds)+len(wgb.fns))
		for _, f := range *wgb.flds {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	selector.GroupBy(selector.Columns(*wgb.flds...)...)
	if err := selector.Err(); err != nil {
		return err
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := wgb.build.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

// WeatherSelect is the builder for selecting fields of Weather entities.
type WeatherSelect struct {
	*WeatherQuery
	selector
}

// Aggregate adds the given aggregation functions to the selector query.
func (ws *WeatherSelect) Aggregate(fns ...AggregateFunc) *WeatherSelect {
	ws.fns = append(ws.fns, fns...)
	return ws
}

// Scan applies the selector query and scans the result into the given value.
func (ws *WeatherSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, ws.ctx, "Select")
	if err := ws.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*WeatherQuery, *WeatherSelect](ctx, ws.WeatherQuery, ws, ws.inters, v)
}

func (ws *WeatherSelect) sqlScan(ctx context.Context, root *WeatherQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(ws.fns))
	for _, fn := range ws.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*ws.selector.flds); {
	case n == 0 && len(aggregation) > 0:
		selector.Select(aggregation...)
	case n != 0 && len(aggregation) > 0:
		selector.AppendSelect(aggregation...)
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := ws.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
